#set(notfmt="@formatter:off")
#set(javaType=getJavaType(fieldModel))
#set(fieldConfigObject=fieldModel.toFieldConfig())
<form class="layui-form detail_form form-table-edit" action="" lay-filter="field_config_edit_form">
    #switch (javaType)
        #case ('Integer','Long','Double','Float','BigDecimal')<!-- 数据库表列表 -->
    <div class="layui-form-item">
        <label class="layui-form-label">自动递增</label>
        <div class="layui-input-block">
            <input type="checkbox" name="isAutoIncrease" lay-verify="" title="是" #(fieldConfigObject.isAutoIncrease()?'checked':'')>
        </div>
    </div>
    #end
    <div class="layui-form-item">
        <label class="layui-form-label">关联类型</label>
        <div class="layui-input-block">
            <select name="releaseType" lay-verify="" lay-filter="releaseType">
                <option value="none">无</option>
                <option value="table">表关联</option>
                <option value="dic">字典关联</option>
                <option value="enum">枚举关联</option>
                <option value="sql">SQL关联</option>
            </select>
        </div>
    </div>
    <div id="config_dyn_area" class="field_config_area">

    </div>

    <div class="detail_form_footer">
        <a class="layui-btn" lay-submit lay-filter="btn_field_config_submit">保存</a>
        <a class="layui-btn layui-btn-primary" lay-filter="btn_field_config_cancle">取消</a>
    </div>
</form>


<!-- 表关联配置区 -->
<div id="table_config_area_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">关联表</label>
        <div class="layui-input-block">
            <select id="release_table_select_temp" name="release_table" lay-verify="required" xm-select-search="" xm-select-radio=""
                    placeholder="选择关联表" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="release_table_select_temp" lay-filter="release_table_select_temp">
                <option value="">选择关联表</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">关联字段</label>
        <div class="layui-input-block">
            <select id="release_field_key_select_temp" name="release_field_key" lay-verify="required" xm-select-search="" xm-select-radio=""
                    placeholder="选择关联字段" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="release_field_key_select_temp" lay-filter="release_field_key_select_temp">
                <option value="">选择关联字段</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">显示字段</label>
        <div class="layui-input-block">
            <select id="release_field_title_select_temp" name="release_field_title" lay-verify="required" xm-select-search="" xm-select-radio=""
                    placeholder="选择显示字段" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="release_field_title_select_temp" lay-filter="release_field_title_select_temp">
                <option value="">选择显示字段</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">上级字段</label>
        <div class="layui-input-block">
            <select id="release_field_pkey_select_temp" name="release_field_pkey" lay-verify="" xm-select-search="" xm-select-radio=""
                    placeholder="选择上级字段" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="release_field_pkey_select_temp" lay-filter="release_field_pkey_select_temp">
                <option value="">选择上级字段</option>
            </select>
        </div>
    </div>
</div>

<!-- 字典关联配置区 -->
<div id="dic_config_area_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">选择字典</label>
        <div class="layui-input-block">
            <select id="release_dic_select_temp" name="release_dic" lay-verify="required" xm-select-search="" xm-select-radio=""
                    placeholder="选择关联字典" autocomplete="off" xm-select-height="38px" xm-select-skin="normal" xm-select="release_dic_select_temp" lay-filter="release_dic_select_temp">
                <option value="">选择关联字典</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">关联值</label>
        <div class="layui-input-block">
            <select name="release_dic_value_type" lay-verify="" lay-filter="release_dic_value_type_select_temp">
                <option value="id">字典编号</option>
                <option value="code">字典代码</option>
                <option value="value">字典值</option>
            </select>
        </div>
    </div>
</div>

<!-- SQL关联配置区 -->
<div id="sql_config_area_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">关联SQL</label>
        <div class="layui-input-block">
            <textarea name="release_sql" lay-verify="required" placeholder="关联SQL查询语句" class="layui-textarea">#(fieldConfigObject.releaseConfig.getConfig('sql'))</textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">关联字段</label>
        <div class="layui-input-block">
            <input type="text" name="release_sql_field_key" required lay-verify="required" value="#(fieldConfigObject.releaseConfig.getConfig('sqlFieldKey'))" placeholder="请输入SQL关联字段" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">显示字段</label>
        <div class="layui-input-block">
            <input type="text" name="release_sql_field_title" required lay-verify="required" value="#(fieldConfigObject.releaseConfig.getConfig('sqlFieldTitle'))" placeholder="请输入SQL显示字段" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">上级字段</label>
        <div class="layui-input-block">
            <input type="text" name="release_sql_field_pkey" required lay-verify="" value="#(fieldConfigObject.releaseConfig.getConfig('sqlFieldPKey'))" placeholder="请输入SQL上级字段(可选)" autocomplete="off" class="layui-input">
        </div>
    </div>
</div>

<!-- 枚举关联配置区 -->
<div id="enum_config_area_temp" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">枚举选项</label>
        <div class="layui-input-block">
            <!-- 列表表格 -->
            <table id="enum_config_table" lay-filter="enum_config_table" style="width: 100%"></table>
            <!-- 显示名称 -->
            <script type="text/html" id="enum_title">
                <input type="text" name="enum_title_{{d.no}}" value="{{d.title?d.title:''}}" required lay-verify="required" placeholder="显示名称" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="enum_value">
                <input type="text" name="enum_value_{{d.no}}" value="{{d.value?d.value:''}}" required lay-verify="required" placeholder="值" autocomplete="off" class="layui-input">
            </script>
            <script type="text/html" id="enum_oper">
                <a class="layui-btn layui-btn-xs" lay-event="add"><i class="layui-icon layui-icon-add-1"></i>添加</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
            </script>
        </div>
    </div>
</div>

<script>
    layui.use(['admin', 'form', 'laydate', 'formSelects'], function () {
        var $ = layui.$
            , admin = layui.admin
            , element = layui.element
            , layer = layui.layer
            , laydate = layui.laydate
            , table = layui.table
            , formSelects = layui.formSelects
            , form = layui.form;
        var thisDialogIndex = layer.index;

        form.render(null, 'field_config_edit_form');

        //枚举表格列定义
        let enumTableCols = [[
            {field: 'title', align: 'center', title: '显示名称', event: 'title', templet: "#enum_title"},
            {field: 'value', align: 'center', title: '值', event: 'value', templet: "#enum_value"},
            {title: '操作', fixed: 'right', width: 150, templet: '#enum_oper'}
        ]]

        form.on("select(releaseType)", function (d) {
            let selectValue = d.value;
            renderConfigArea(selectValue)
        })

        form.val("field_config_edit_form", {
            releaseType: '#(fieldConfigObject.releaseType!=null?fieldConfigObject.releaseType:"none")',
        })

        #set(table = fieldConfigObject.releaseConfig.getConfig("table"))
        #set(fieldKey = fieldConfigObject.releaseConfig.getConfig("fieldKey"))
        #set(fieldPKey = fieldConfigObject.releaseConfig.getConfig("fieldPKey"))
        #set(fieldTitle = fieldConfigObject.releaseConfig.getConfig("fieldTitle"))
        #set(dicId = fieldConfigObject.releaseConfig.getConfig("dicId"))
        #set(dicVType = fieldConfigObject.releaseConfig.getConfig("dicVType"))
        #set(enumList = fieldConfigObject.releaseConfig.getConfig("enumList"))
        #if(fieldConfigObject.releaseType != null && !"none".equals(fieldConfigObject.releaseType))
            // 初始化关联类型选择
            renderConfigArea('#(fieldConfigObject.releaseType)');
            #if(table != null)
            // 初始化字段选择
            renderFieldConfigSelect('#(table)');
            #end
            #if(table != null)
            formSelects.value("release_table_select", ['#(table)'])
            #end
            #if(fieldKey != null)
            formSelects.value("release_field_key_select", ['#(fieldKey)'])
            #end
            #if(notBlank(fieldPKey))
            formSelects.value("release_field_pkey_select", ['#(fieldPKey)'])
            #end
            #if(fieldTitle != null)
            formSelects.value("release_field_title_select", ['#(fieldTitle)'])
            #end
            #if(dicId != null)
            formSelects.value("release_dic_select", ['#(dicId)'])
            #end
            #if(dicVType != null)
            form.val("field_config_edit_form", {"release_dic_value_type": '#(dicVType)'});
            #end
            #if(enumList != null)
            renderEnumConfigTable(JSON.parse('#(enumList)'))
            #end
        #end

        // 渲染关联表字段选择
        function renderFieldConfigSelect(tableKey) {
            function bf(id, searchUrl, inputValue, res) {
                if (res && res.data && res.data.forEach) {
                    res.data.forEach(function (item) {
                        item.title = item.COLUMN_NAME + (item.COLUMN_COMMENT ? "(" + item.COLUMN_COMMENT + ")" : "");
                    });
                }
                return res;
            }

            let formSelectConfig = {
                url: '/generator/table/dbFieldList?table_key=' + (tableKey ? tableKey : 'none'),
                keyName: 'title',
                keyVal: 'COLUMN_NAME',
                beforeSuccess: bf,
                searchName: 'field_title__op__like',
                showPage: true,
                size: 10,
            };
            formSelects.data('release_field_key_select', 'server', formSelectConfig);
            formSelects.data('release_field_title_select', 'server', formSelectConfig);
            formSelects.data('release_field_pkey_select', 'server', formSelectConfig);
        }

        // 渲染动态配置区域
        function renderConfigArea(releaseType) {
            $('#config_dyn_area').html("");
            if (releaseType && releaseType != 'none') {
                let html = $('#' + releaseType + '_config_area_temp').html();
                $('#config_dyn_area').html(html.replace(/_temp/g, ""));
                form.render(null, 'field_config_edit_form');
                switch (releaseType) {
                    case 'table':
                        //渲染数据库表下拉选择器
                        formSelects.data('release_table_select', 'server', {
                            url: '/generator/table/dbTableList',
                            keyName: 'TABLE_TITLE',
                            keyVal: 'TABLE_NAME',
                            searchName: 'table_title__op__like',
                            showPage: true,
                            size: 999,
                        });
                        formSelects.on('release_table_select', function (id, vals, val, isAdd, isDisabled) {
                            if (isAdd) {
                                let infos = val.name.split('(');
                                let tableKey = infos.length > 0 ? infos[0] : '';
                                renderFieldConfigSelect(tableKey);
                            }
                        }, true);
                        break;
                    case 'dic':
                        //渲染字典下拉选择器
                        formSelects.data('release_dic_select', 'server', {
                            url: '/system/dic/list?dic_pid=0',
                            keyName: 'dic_name',
                            keyVal: 'dic_id',
                            searchName: 'dic_name__op__like',
                            showPage: true,
                            size: 10,
                        });
                    case 'enum':
                        renderEnumConfigTable([])
                        break;
                }
            }

        }

        function renderEnumConfigTable(data) {
            if (!data || data.length <= 0) {
                data = [{title: "", value: ""}]
            }
            // 重新设置排序号
            data.forEach((item, idx) => item.no = idx + 1);
            table.render({
                id: "enum_config_table",
                elem: '#enum_config_table',
                data: data,
                cols: enumTableCols,
                limit: 999,
            })
            // 监听表格行事件
            table.on("tool(enum_config_table)", tableEventListener);
        }

        // 添加表格数据
        function addTableData(tableData, preData) {
            let newTableData = [];
            let isAdd = false;
            for (let i = 0; i < tableData.length; i++) {
                newTableData.push(tableData[i]);
                if (preData != null) {
                    if (preData.no == tableData[i].no) {
                        newTableData.push({})
                        isAdd = true;
                    }
                }
            }
            if (!isAdd) {
                newTableData.push({})
            }
            return newTableData;
        }

        // 删除表格数据
        function removeTableData(tableData, data) {
            let newTableData = [];
            for (let i = 0; i < tableData.length; i++) {
                if (data != null) {
                    if (data.no == tableData[i].no) {
                        continue;
                    }
                }
                newTableData.push(tableData[i]);
            }
            return newTableData;
        }


        // 事件监听
        function tableEventListener(obj) {
            let event = obj.event;
            let data = obj.data;
            switch (event) {
                case 'add':
                    renderEnumConfigTable(addTableData(getEnumList(), data));
                    break;
                case 'del':
                    renderEnumConfigTable(removeTableData(getEnumList(), data));
                    break;
            }
        }

        function getEnumList() {
            let formVals = form.val("field_config_edit_form");
            let enumList = [];
            Object.keys(formVals).forEach(function (key) {
                if (key.indexOf("enum_title_") >= 0) {
                    let no = key.substring(11);
                    enumList.push({
                        title: formVals[key],
                        value: formVals["enum_value_" + no],
                        no: no,
                    })
                }
            })
            enumList = enumList.sort(function (a, b) {
                return a.no - b.no
            })
            return enumList;
        }

        /* 监听提交 */
        form.on('submit(btn_field_config_submit)', function (data) {
            let formVals = form.val("field_config_edit_form");
            let fieldConfig = {};
            fieldConfig.isAutoIncrease = formVals.isAutoIncrease == 'on';
            fieldConfig.releaseType = formVals.releaseType;
            fieldConfig.releaseConfig = {
                config: {
                    'table': {
                        "configZhName": "关联表",
                        "configName": "table",
                        "configValue": formVals.release_table,
                    },
                    'fieldKey': {
                        "configZhName": "关联字段",
                        "configName": "fieldKey",
                        "configValue": formVals.release_field_key,
                    },
                    'fieldTitle': {
                        "configZhName": "显示字段",
                        "configName": "fieldTitle",
                        "configValue": formVals.release_field_title,
                    },
                    'fieldPKey': {
                        "configZhName": "上级字段",
                        "configName": "fieldPKey",
                        "configValue": formVals.release_field_pkey,
                    },
                    'dicId': {
                        "configZhName": "关联字典",
                        "configName": "dicId",
                        "configValue": formVals.release_dic,
                    },
                    'dicVType': {
                        "configZhName": "关联值",
                        "configName": "dicVType",
                        "configValue": formVals.release_dic_value_type,
                    },
                    'sql': {
                        "configZhName": "关联SQL语句",
                        "configName": "sql",
                        "configValue": formVals.release_sql,
                    },
                    'sqlFieldKey': {
                        "configZhName": "SQL关联字段",
                        "configName": "sqlFieldKey",
                        "configValue": formVals.release_sql_field_key,
                    },
                    'sqlFieldTitle': {
                        "configZhName": "SQL显示字段",
                        "configName": "sqlFieldTitle",
                        "configValue": formVals.release_sql_field_title,
                    },
                    'sqlFieldPKey': {
                        "configZhName": "上级字段",
                        "configName": "sqlFieldPKey",
                        "configValue": formVals.release_sql_field_pkey,
                    },
                    'enumList': {
                        "configZhName": "枚举列表",
                        "configName": "enumList",
                        "configValue": JSON.stringify(getEnumList()),
                    },
                }
            };
            updateFieldConfigTable('#(fieldModel.field_id)', JSON.stringify(fieldConfig));
            // form.val("table_model_edit_form",{'field_config_#(fieldModel.field_id)': JSON.stringify(fieldConfig)});
            layer.close(thisDialogIndex);
            return false;
        });

        function updateFieldConfigTable(fieldId, fieldConfig) {
            let tableData = table.cache.field_config_table;
            let newTableData = []
            if (tableData && tableData.length > 0) {
                tableData.forEach(function (item) {
                    let newItem = table.fun.field_config_table.getFieldModel(item)
                    if (newItem.field_id == fieldId) {
                        newItem.field_config = fieldConfig
                    }
                    newTableData.push(newItem)
                })
                // 更新配置结果
                table.render({
                    id: "field_config_table",
                    elem: '#field_config_table',
                    data: newTableData,
                    cols: table.field_config_table_cols,
                    limit: 999,
                })
            }
        }

        /* 监听取消 */
        $("[lay-filter=btn_field_config_cancle]").click(function () {
            layer.close(layer.index);
        });

    })
</script>